package cn.cloudtogo.common.types;

import cn.cloudtogo.common.GendbException;
import cn.cloudtogo.common.model.ExternalDatasourceModel;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Base64;

import static cn.cloudtogo.common.GendbGlobalConstant.DATASOURCE_KEY;


/**
 * @author yaolianhua789@gmail.com
 **/
@Data
@Slf4j
public class RequestHeaderObject {

    @JsonProperty(DATASOURCE_KEY)
    private String uuid;
    @JsonIgnore
    private String encodeData;

    private static RequestHeaderObject of(String uuid, String encodeData) {
        RequestHeaderObject requestHeaderObject = new RequestHeaderObject();
        requestHeaderObject.setUuid(uuid);
        requestHeaderObject.setEncodeData(encodeData);
        return requestHeaderObject;
    }

    public static ExternalDatasourceModel extractExternalDatasourceModel(RequestHeaderObject requestHeaderObject) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule()).configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        try {
            byte[] bytes = Base64.getDecoder().decode(requestHeaderObject.getEncodeData());
            ExternalDatasourceModel model = objectMapper.readValue(new String(bytes), ExternalDatasourceModel.class);
            return model;
        } catch (JsonProcessingException e) {
            log.error("can not read json string [{}]", e.getMessage(), e);
            throw new GendbException("key is invalid");
        }
    }

    public static RequestHeaderObject ofModel(ExternalDatasourceModel model) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule()).configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        try {
            String asString = objectMapper.writeValueAsString(model);
            return of(model.getUuid(), Base64.getEncoder().encodeToString(asString.getBytes()));
        } catch (JsonProcessingException e) {
            log.error("can not write json string [{}]", e.getMessage(), e);
            throw new GendbException("server error");
        }
    }

}
